<template>
    <div class="article-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <Document />
                        </el-icon>
                        <span>文章管理</span>
                    </div>
                    <div class="header-right">
                        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleStatusChange"
                            class="status-filter">
                            <el-option label="审核中" :value="0" />
                            <el-option label="已发布" :value="1" />
                        </el-select>
                        <div class="search-box">
                            <el-input v-model="searchQuery" placeholder="请输入文章标题搜索" clearable @clear="handleSearch"
                                @keyup.enter="handleSearch">
                                <template #suffix>
                                    <el-icon class="search-icon" @click="handleSearch">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                    </div>
                </div>
            </template>

            <el-table :data="articleList" style="width: 100%" v-loading="loading" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 500
            }">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="coverImage" label="封面" width="120">
                    <template #default="{ row }">
                        <el-image :src="row.coverImage" fit="cover" class="cover-image" />
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="标题">
                    <template #default="{ row }">
                        <span class="title-preview" @click="handleView(row)">
                            {{ row.title }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="简介">
                    <template #default="{ row }">
                        {{ getContentPreview(row.description) }}
                    </template>
                </el-table-column>
                <el-table-column label="数据统计" align="center">
                    <template #default="{ row }">
                        <div class="stats">
                            <span>
                                <el-icon>
                                    <View />
                                </el-icon>
                                {{ row.viewCount }}
                            </span>
                            <span>
                                <el-icon>
                                    <Star />
                                </el-icon>
                                {{ row.likeCount }}
                            </span>
                            <span>
                                <el-icon>
                                    <ChatDotRound />
                                </el-icon>
                                {{ row.commentCount }}
                            </span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                            {{ row.status === 1 ? '已发布' : '审核中' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="180">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleView(row)">
                            <el-icon>
                                <View />
                            </el-icon>查看
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[8, 10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
            </div>
        </el-card>

        <!-- 文章详情对话框 -->
        <el-dialog title="文章详情" v-model="viewDialogVisible" width="800px">
            <div class="article-detail">
                <div class="article-header">
                    <h2>{{ currentArticle?.title }}</h2>
                    <div class="article-meta">
                        <span>创建时间：{{ formatDateTime(currentArticle?.createTime) }}</span>
                        <el-tag :type="currentArticle?.status === 1 ? 'success' : 'warning'">
                            {{ currentArticle?.status === 1 ? '已发布' : '审核中' }}
                        </el-tag>
                    </div>
                </div>
                <div class="article-cover" v-if="currentArticle?.coverImage">
                    <el-image :src="currentArticle.coverImage" fit="cover" />
                </div>
                <div class="article-description">
                    <h3>文章简介：</h3>
                    <p>{{ currentArticle?.description }}</p>
                </div>
                <div class="article-content">
                    <h3>文章内容：</h3>
                    <div v-html="currentArticle?.content"></div>
                </div>
                <div class="article-stats">
                    <span>
                        <el-icon>
                            <View />
                        </el-icon>
                        浏览：{{ currentArticle?.viewCount }}
                    </span>
                    <span>
                        <el-icon>
                            <Star />
                        </el-icon>
                        点赞：{{ currentArticle?.likeCount }}
                    </span>
                    <span>
                        <el-icon>
                            <ChatDotRound />
                        </el-icon>
                        评论：{{ currentArticle?.commentCount }}
                    </span>
                </div>
            </div>
            <template #footer>
                <el-button @click="viewDialogVisible = false">关闭</el-button>
                <el-button v-if="currentArticle?.status === 0" type="primary" @click="handleApprove"
                    :loading="approving">
                    审核通过
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Search, View, Star, ChatDotRound, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const articleList = ref([])
const searchQuery = ref('')
const statusFilter = ref(null)
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 查看详情相关
const viewDialogVisible = ref(false)
const currentArticle = ref(null)
const approving = ref(false)

// 获取文章列表
const getArticleList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/article/list',
            method: 'get',
            params: {
                page: currentPage.value,
                size: pageSize.value,
                title: searchQuery.value,
                status: statusFilter.value
            }
        })
        articleList.value = res.data.records
        total.value = res.data.total
    } catch (error) {
        console.error('获取文章列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

// 获取内容预览
const getContentPreview = (content) => {
    if (!content) return ''
    return content.length > 50 ? content.substring(0, 50) + '...' : content
}

// 查看文章
const handleView = (row) => {
    currentArticle.value = row
    viewDialogVisible.value = true
}

// 审核通过
const handleApprove = async () => {
    if (!currentArticle.value) return

    approving.value = true
    try {
        await request({
            url: `/article/approve/${currentArticle.value.id}`,
            method: 'put'
        })
        currentArticle.value.status = 1
        // 更新列表中的状态
        const index = articleList.value.findIndex(item => item.id === currentArticle.value.id)
        if (index !== -1) {
            articleList.value[index].status = 1
        }
        ElMessage.success('审核通过')
        viewDialogVisible.value = false
    } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('操作失败')
    } finally {
        approving.value = false
    }
}

// 搜索和筛选
const handleSearch = () => {
    currentPage.value = 1
    getArticleList()
}

const handleStatusChange = () => {
    currentPage.value = 1
    getArticleList()
}

// 分页相关
const handleSizeChange = (val) => {
    pageSize.value = val
    getArticleList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getArticleList()
}

// 删除文章
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该文章吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await request({
                url: '/article/delete',
                method: 'post',
                data: [row.id]
            })
            ElMessage.success('删除成功')
            getArticleList()
        } catch (error) {
            console.error('删除失败:', error)
        }
    })
}

onMounted(() => {
    getArticleList()
})
</script>

<style scoped>
.article-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

.search-box {
    width: 250px;
}

.status-filter {
    width: 120px;
}

.cover-image {
    width: 80px;
    height: 60px;
    border-radius: 4px;
}

.title-preview {
    cursor: pointer;
    color: #409EFF;
}

.title-preview:hover {
    opacity: 0.8;
}

.stats {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.stats span {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #606266;
}

.article-detail {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
}

.article-header {
    margin-bottom: 20px;
}

.article-header h2 {
    margin: 0 0 10px 0;
}

.article-meta {
    display: flex;
    align-items: center;
    gap: 16px;
    color: #606266;
}

.article-cover {
    margin: 20px 0;
}

.article-cover .el-image {
    max-width: 100%;
    max-height: 300px;
    border-radius: 4px;
}

.article-description,
.article-content {
    margin: 20px 0;
}

.article-description h3,
.article-content h3 {
    margin-bottom: 10px;
    color: #303133;
}

.article-stats {
    margin-top: 20px;
    display: flex;
    gap: 20px;
    color: #606266;
}

.article-stats span {
    display: flex;
    align-items: center;
    gap: 4px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}
</style>